package com.dynamicthreadpool.netty.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * 线程池消息解码器
 */
public class ThreadPoolMessageDecoder extends ByteToMessageDecoder {
    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 确保至少有4个字节可读（消息长度）
        if (in.readableBytes() < 4) {
            return;
        }
        
        // 标记当前读取位置
        in.markReaderIndex();
        
        // 读取消息长度
        int messageLength = in.readInt();
        
        // 如果可读字节数小于消息长度，重置读取位置并返回
        if (in.readableBytes() < messageLength) {
            in.resetReaderIndex();
            return;
        }
        
        // 读取消息内容
        byte[] messageBytes = new byte[messageLength];
        in.readBytes(messageBytes);
        
        // 反序列化消息
        ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        ThreadPoolControlMessage message = (ThreadPoolControlMessage) ois.readObject();
        
        out.add(message);
        
        ois.close();
        bais.close();
    }
}